package com.example.housingRentalSystem.service.Impl;


import com.example.housingRentalSystem.bean.House;
import com.example.housingRentalSystem.mapper.HouseImagesMapper;
import com.example.housingRentalSystem.mapper.HouseMapper;
import com.example.housingRentalSystem.service.FileService;
import com.example.housingRentalSystem.service.HouseService;

import com.example.housingRentalSystem.utils.ApiResponse;
import com.example.housingRentalSystem.utils.PageRequest;
import com.example.housingRentalSystem.utils.PageResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class HouseServiceImpl implements HouseService {

    @Autowired
    HouseMapper houseMapper;
    @Autowired
    HouseImagesMapper houseImagesMapper;
    @Autowired
    FileService fileService;


    private static final Logger logger = LoggerFactory.getLogger(FeedbackServiceImpl.class);


    @Override
    public PageResponse<House> selectHouse(
            String city, String rentType, Integer minRent, Integer maxRent, String sortBy,
            String order, Integer status, Integer ownerId, Integer id,String title,PageRequest pageRequest) {

        if (pageRequest == null) {
            pageRequest = new PageRequest();
        }
        pageRequest.validate();
        PageHelper.startPage(
                pageRequest.getPage() != null ? pageRequest.getPage() : 1,
                pageRequest.getSize() != null ? pageRequest.getSize() : 10
        );
        Page<House> page = houseMapper.selectHouse(city, rentType, minRent, maxRent, sortBy, order, status, ownerId, id, title);

        if (page == null || page.getResult() == null) {
            return PageResponse.empty();
        }

        List<House> houseList = Optional.ofNullable(page.getResult())
                .orElse(Collections.emptyList());
        houseList.forEach(house -> {
            List<String> images = houseImagesMapper.selectImagesByHouseId(house.getId());
            house.setHouseImageList(images != null ? images : Collections.emptyList());
        });

        return PageResponse.build(page);
    }



    @Override
    public ApiResponse<String> addHouse(House house, List<MultipartFile> images) {
        try {
            // 1. 基础校验
            if (house.getOwnerId() == null) {
                return ApiResponse.error(400, "房东ID不能为空");
            }

            int affected = houseMapper.insertHouse(house);
            if (affected <= 0 || house.getId() == null) {
                throw new RuntimeException("房源信息保存失败");
            }

            // 4. 处理图片上传
            if (CollectionUtils.isNotEmpty(images)) {
                List<String> imageUrls = images.stream()
                        .filter(file -> !file.isEmpty())
                        .map(file -> {
                            String url = fileService.uploadImage(file);
                            if (url == null) {
                                throw new RuntimeException("图片上传失败");
                            }
                            return url;
                        })
                        .collect(Collectors.toList());

                // 5. 保存图片关联记录
                houseImagesMapper.batchInsertImages(house.getId(), imageUrls);
            }

            return ApiResponse.success("房源提交成功，等待审核");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("房源发布失败: {}", e.getMessage());
            return ApiResponse.error(500, "房源发布失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> updateHouse(Integer userId, House house, List<MultipartFile> images) {
        try {
            // 校验房源归属
            House existingHouse = houseMapper.selectHouseById(house.getId());
            if (existingHouse == null) {
                return ApiResponse.error(404, "房源不存在");
            }
            if (!existingHouse.getOwnerId().equals(userId)) {
                return ApiResponse.error(403, "无权修改此房源");
            }

            // 更新基本信息
            house.setUpdateTime(new Date());
            if (houseMapper.updateHouse(house) <= 0) {
                throw new RuntimeException("更新失败");
            }

            // 处理图片（若传参）
            if (images != null) {
                houseImagesMapper.deleteByHouseId(house.getId());

                if (!images.isEmpty()) {
                    List<String> urls = images.stream()
                            .map(fileService::uploadImage)
                            .collect(Collectors.toList());
                    houseImagesMapper.batchInsertImages(house.getId(), urls);
                }
            }

            return ApiResponse.success("更新成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("更新失败: {}", e.getMessage());
            return ApiResponse.error(500, "更新失败: " + e.getMessage());
        }
    }


    @Override
    @Transactional
    public void updateHouseStatus(Integer houseId, Integer status) {
        if (houseId == null || houseId <= 0) {
            throw new IllegalArgumentException("无效的房屋ID");
        }
        if (!List.of(-3,-2,-1, 1,2,3).contains(status)) {
            throw new IllegalArgumentException("非法的状态值");
        }

        int affected = houseMapper.updateHouseStatus(houseId, status);
        if (affected == 0) {
            throw new RuntimeException("房屋不存在或状态未变化");
        }
    }

    @Override
    public int selectHouseCount() {
        int count = houseMapper.selectHouseCount();
        return count;
    }

    @Override
    public List<Map<String, Object>> getNewHousesCountByDayThisWeek() {
        return houseMapper.findNewHousesCountByDayThisWeek();
    }

    @Override
    public ApiResponse<String> addHouseAndImage(House house, List<MultipartFile> images) {
        return null;
    }

    @Override
    public List<House> selectHouseByOwnerId(Integer ownerId) {
        List<House> houses = houseMapper.selectHouseByOwnerId(ownerId);
        if (houses != null && !houses.isEmpty()) {
            houses.forEach(house -> {
                List<String> images = houseImagesMapper.selectImagesByHouseId(house.getId());
                house.setHouseImageList(images != null ? images : Collections.emptyList());
            });
        }
        return houses;
    }

    @Override
    public List<House> selectHouseByStatus(Integer status) {
        List<House> houses = houseMapper.selectHouseByStatus(status);
        if (houses != null && !houses.isEmpty()) {
            houses.forEach(house -> {
                List<String> images = houseImagesMapper.selectImagesByHouseId(house.getId());
                house.setHouseImageList(images != null ? images : Collections.emptyList());
            });
        }
        return houses;
    }
}